﻿using System;
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;
using Auth.Application;
using Auth.Web.Models;
using Auth.Application.Dtos;
using SqlSugar;
using Auth.SqlSugar;

namespace Auth.Web.Controllers
{
    public class DepartmentController : AuthControllerBase
    {
        private readonly IDepartmentAppService _service;
        public DepartmentController( IDepartmentAppService service)
        {
            _service = service;
        }
        

        public IActionResult Index()
        {
            return View();
        }

        public IActionResult EditPage(string id, string pid)
        {
            bool isAdd = string.IsNullOrEmpty(id);
            id = string.IsNullOrEmpty(id) ? pid : id;
            ViewData["id"] = id;
            ViewData["isAdd"] = isAdd;
            return View();
        }

        /// <summary>
        /// 获取表格头
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public JsonResult GetDepartmentTableCols()
        {
            List<LayuiColsModel> colsList = new List<LayuiColsModel>();
            colsList = GetTableCols<DepartmentDto>();
            return Json(new ReturnModel() { Data = colsList });
        }

        /// <summary>
        /// 获取部门 树形表格json数据
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public JsonResult GetDepartTreeTable(string searchParam, string field, string order)
        {
            var orderField = " No asc ";
            if (string.IsNullOrEmpty(field))
                orderField = field + " " + order;
            List<IConditionalModel> conModels = ConditionHelper.GetCondition(searchParam);
            conModels.Add(new ConditionalModel()
            {
                FieldName = "isDeleted",
                ConditionalType = ConditionalType.Equal,
                FieldValue = "0"
            });
            var result = _service.GetTableList(1, 100000, conModels, orderField);
            return Json(result);
        }


        /// <summary>
        /// 获取功能树JSON数据
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetTreeData()
        {
            var dtos = _service.GetAllList();
            List<TreeModel> treeModels = new List<TreeModel>();
            foreach (var dto in dtos)
            {
                treeModels.Add(new TreeModel() { Id = dto.Id, Text = dto.Name, Parent = dto.ParentId == Guid.Empty.ToString() ? "0" : dto.ParentId });
            }
            
            return Json(new ReturnModel{Data = treeModels});
        }

        /// <summary>
        /// 获取下拉树JSON数据
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetSelectData()
        {
            var dtos = _service.QueryAll(s=>s.No.Length==3);
            List<SelectTree> treeModels = new List<SelectTree>();
            foreach (var dto in dtos)
            {
                treeModels.Add(new SelectTree() { Value = dto.Id, Name = dto.Name,Children = GetChildren(dto.Id) });
            }

            return Json(treeModels);
        }

        /// <summary>
        /// 获取 下级部门
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public List<SelectTree> GetChildren(string id)
        {
            var result = _service.QueryAll(s => s.ParentId == id);
            List<SelectTree> treeModels = new List<SelectTree>();
            foreach (var item in result)
            {
                if (_service.QueryAll(s => s.ParentId == item.Id).Count>0)
                {
                    treeModels.Add(new SelectTree() { Value = item.Id, Name = item.Name,Children = GetChildren(item.Id) }); 
                }
                else
                {
                    treeModels.Add(new SelectTree() { Value = item.Id, Name = item.Name, Children = null});
                }
            }
            return treeModels;
        }

        /// <summary>
        /// 获取子级列表
        /// </summary>
        /// <returns></returns>
        public IActionResult GetChildrenByParent(string parentId, int page, int limit = 15)
        {
            List<IConditionalModel> conModels = new List<IConditionalModel>
            {
                new ConditionalModel()
                {
                    FieldName = "parentId",
                    ConditionalType = ConditionalType.Equal,
                    FieldValue = parentId
                }
            };
            var result = _service.GetTableList(page, limit, conModels);
            return Json(result);
        }

        /// <summary>
        /// 新增或编辑功能
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public IActionResult Edit(DepartmentDto dto)
        {
            ReturnModel r = new ReturnModel
            {
                Success = false,
                Msg = "操作失败！"
            };
            if (!ModelState.IsValid)
            {
                return Json(r);
            }

            if (_service.InsertOrUpdate(dto))
            {
                return Json(new ReturnModel {Success = true, Msg = "操作成功！"});
            }

            return Json(r);
        }

        public IActionResult DeleteMuti(string ids)
        {
            ReturnModel r = new ReturnModel
            {
                Success = false,
                Msg = "操作失败！"
            };
            try
            {
                string[] idArray = ids.Split(',');
                List<string> delIds = new List<string>();
                foreach (string id in idArray)
                {
                    delIds.Add(id);
                }

                _service.Delete(delIds);
                return Json(new ReturnModel() {Success = true, Msg = "操作成功！"});
            }
            catch (Exception ex)
            {
                r.Msg = ex.Message;
                return Json(r);
            }
        }
        public IActionResult Delete(string id)
        {
            ReturnModel r = new ReturnModel
            {
                Success = false,
                Msg = "操作失败！"
            };
            _service.Delete(id);
            return Json(new ReturnModel() { Success = true, Msg = "操作成功！" });
        }
        public IActionResult Get(string id, bool isAdd)
        {
            var depart = new DepartmentDto();
            if (!isAdd)
            {
                depart = _service.QuerySingle(id);
            }
            else
            {
                depart.ParentId = id;
                depart.No = _service.GetNextNo(id);
            }

            return Json(new ReturnModel() { Data = depart });
        }
    }
}